#!/bin/bash

# salt的控制脚本

CURRENT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd)"
THIS_SCRIPT="${CURRENT_DIR}/$(basename $0)"
PROJECT_FOLDER="$(dirname $(dirname ${CURRENT_DIR}))"

# 解决python的ssl依赖问题
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:${PROJECT_FOLDER}/component/env/lib/

APP_NAME="salt"
PYTHON3="${PROJECT_FOLDER}/component/env/bin/python3"
SALT_CONFIG_DIR="${PROJECT_FOLDER}/config/salt"
SALT_PID_FILE="${PROJECT_FOLDER}/logs/salt-master.pid"
SALT_LOG_FILE="${PROJECT_FOLDER}/logs/salt-master.log"

start() {
  real_status
  if [ $? -eq 0 ];then
    echo "${APP_NAME} [running]"
    return 0
  else
    ${PYTHON3} ${PROJECT_FOLDER}/component/env/bin/salt-master \
      -c ${SALT_CONFIG_DIR} \
      --pid-file ${SALT_PID_FILE} \
      --log-file=${SALT_LOG_FILE} \
      --log-file-level=error \
      -d
    echo "${APP_NAME} [running]"
  fi
}

stop() {
  real_status
  if [ $? -eq 1 ]; then
    echo "${APP_NAME} [not running]"
    return 0
  else
    ps -ef | grep "${PROJECT_FOLDER}/component/env/bin/salt-master" | grep -v grep | cut -c 9-15 | xargs kill -9
    sleep 3
    real_status
    if [ $? -eq 0 ]; then
      echo "${APP_NAME} [running]"
      return 1
    else
      echo "${APP_NAME} [not running]"
      return 0
    fi
  fi
}

real_status() {
  salt_master_num=$(ps -ef | grep ${PROJECT_FOLDER}/component/env/bin/salt-master | grep -v grep | wc -l)
  if [ $salt_master_num -gt 10 ]; then
    return 0
  else
    return 1
  fi
}

status() {
  real_status
  if [ $? -eq 0 ]; then
    echo "${APP_NAME} [running]"
    return 0
  else
    echo "${APP_NAME} [not running]"
    return 1
  fi
}

case $1 in
start) start ;;
stop) stop ;;
restart)
  stop
  start
  ;;
status)
  status
  ;;
*)
  echo "usage: $0 [start|stop|restart|status]"
  ;;
esac
